/**
 * Created by zhuang.haipeng on 2017/9/12.
 */
import React, {Component} from 'react';
import {DeviceEventEmitter, Image, ListView, ScrollView, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import StyleUtils from "../../../res/styles/StyleUtils";
import Navigation from "../../../custom/Navigation";
import ViewUtils from "../../../utils/ViewUtils";
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import CommonUtils from "../../../common/CommonUtils";
import ModalListUtils from "../../../utils/ModalListUtils";
import I18n from "../../../res/language/i18n";
import IparInput from "../../../custom/IparInput";

let countryData = [];
let provinceData = [];
export default class EditTax extends Component {

    constructor(props) {
        super(props);
        let data = this.props.userData;
        let splitData = data.business && data.business.tex_area ? data.business.tex_area.split(',') : '';
        let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            selectCountry: splitData[0] ? splitData[0] : '',
            selectProvince: splitData[1] ? splitData[1] : '',
            taxInput: data.business && data.business.personal_tax ? data.business.personal_tax : '',
            modalDialog: false,
            modalDataType: 'country',
            countrySource: ds,
            provinceSource: ds,
            lang: data.lang,
        };
        this.iparNetwork = new IparNetwork()
    }

    componentWillUnmount() {
        this.iparNetwork = null;
    }

    componentDidMount() {
        CommonUtils.showLoading();

        this.getAddressInfo()
    }

    /*获取用户收货地址信息姐*/
    getAddressInfo(name) {
        let names = '';
        if (name !== undefined) {
            names = '&level=' + 1 + '&parent=' + name
        }
        this.iparNetwork.getRequest(SERVER_TYPE.logistics + 'region?', names)
            .then((result) => {
                if (name === undefined) {
                    for (i = 0; i < result.length; i++) {
                        countryData.push(result[i]);
                    }
                    CommonUtils.dismissLoading();

                    this.setState({
                        countrySource: this.state.countrySource.cloneWithRows(result)
                    });
                } else {
                    for (i = 0; i < result.length; i++) {
                        provinceData.push(result[i]);
                    }
                    CommonUtils.dismissLoading();

                    this.setState({
                        provinceSource: this.state.provinceSource.cloneWithRows(result)
                    });
                }


            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                console.log(error);
            })
    }


    /*获取用户TAx Id*/
    getTaxInfo() {

        let formData = new FormData();
        let userInfo = this.props.userData;
        let _texArea = this.state.selectCountry + ',' + this.state.selectProvince;
        let _personal_tax = this.state.taxInput;

        formData.append("user_id", userInfo.main_user_id);
        formData.append("tex_area", _texArea);
        formData.append("personal_tax", _personal_tax);

        this.iparNetwork.getPostFrom(SERVER_TYPE.admin + 'updateUserInfo', formData)
            .then((result) => {
                CommonUtils.dismissLoading();

                if (result.code === 200) {

                    userInfo.tex_area = _texArea;
                    userInfo.personal_tax = _personal_tax;

                    this.props.callback(userInfo);
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                    this.props.navigator.pop();
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
                }
            })
            .catch((error) => {
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                CommonUtils.dismissLoading();

                console.log(error);
            })
    }

    /*dialog item 点击*/
    itemClickListener(index, text) {

        switch (this.state.modalDataType) {
            case 'country':
                this.getAddressInfo(countryData[index].name);
                this.setState({selectCountry: text, modalDialog: false, selectProvince: ''});

                break;
            case 'region1':
                this.setState({
                    selectProvince: text,
                    modalDialog: false,
                });
                break;
        }


    }


    /*showDialog*/
    showDialog(type) {
        switch (type) {
            case 0:
                this.setState({
                    modalDialog: true,
                    modalDataType: 'country'
                });

                break;
            case 1:
                if (provinceData.length > 0) {
                    this.setState({
                        modalDialog: true,
                        modalDataType: 'region1'
                    });
                }
        }
    }

    render() {
        let _dataSource = this.state.countrySource;
        switch (this.state.modalDataType) {
            case 'region1':
                _dataSource = this.state.provinceSource;
                break;
        }

        return (
            <View style={StyleUtils.flex}>
                <Navigation
                    onClickLeftBtn={() => {
                        this.props.navigator.pop()
                    }}
                    leftButtonIcon={require('../../../res/images/ic_back.png')}
                    titleImage={require('../../../res/images/ic_ipar_logo.png')}
                />
                <ModalListUtils
                    close={() => {
                        this.setState({
                            modalDialog: false
                        })
                    }}
                    onPress={(index, text) => this.itemClickListener(index, text)}
                    visible={this.state.modalDialog}
                    dataSource={_dataSource}
                    dataParam={this.state.modalDataType}
                />
                <ScrollView>
                    <View style={{padding: 16}}>
                        {ViewUtils.getTitleView(I18n.t('default.editTaxing'), I18n.t('default.yourTaxingRegion'))}

                        {ViewUtils.getButtunMenu(this.state.selectCountry ? this.state.selectCountry : I18n.t('default.selectCountry'), () => this.showDialog(0))}
                        {ViewUtils.getButtunMenu(this.state.selectProvince ? this.state.selectProvince : I18n.t('default.selectProvince'), () => this.showDialog(1), {marginTop: 16})}

                        <IparInput
                            style={{marginTop: 16}}
                            onChangeText={(valvue) => {
                                this.setState({taxInput: valvue})
                            }}
                            placeholder={this.state.taxInput ? this.state.taxInput : I18n.t('default.taxId')}/>

                        {ViewUtils.getButton(I18n.t('default.submit'), () => {
                            this.onClick()
                        }, {marginTop: 16})}

                    </View>
                </ScrollView>
            </View>
        );
    }

    /*onPressBtn 点击*/
    onClick() {

        if (this.state.selectCountry === '') {
            DeviceEventEmitter.emit('toast', I18n.t('default.selectCountry'))
        } else if (this.state.selectProvince === '') {
            DeviceEventEmitter.emit('toast', I18n.t('default.selectProvince'))
        } else if (this.state.taxInput.trim() === '') {
            DeviceEventEmitter.emit('toast', I18n.t('default.taxId'))
        } else {
            CommonUtils.showLoading();

            this.getTaxInfo()
        }
    }

};

const styles = StyleSheet.create({
    goodsText: {
        flex: 1,
        color: '#0f0f0f',
        paddingRight: 8,
        paddingLeft: 8
    },

    itemBox: {
        height: 80,
        borderBottomWidth: 1,
        borderBottomColor: '#eeeeee',
        flexDirection: 'row'
    },


});